/* Copyright 2012 Pera Champs, Dept. Computer Engineering, University of Peradeniya

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License. */
package com.service.hibernate.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;

public class GenericDAO<T> {
	@SessionTarget
	Session session;
	
	@TransactionTarget
	Transaction transaction;
	
	//Generic method to get all data from a table
	@SuppressWarnings("unchecked")
	public List<T> getAllData(String pojo){
		List<T> resultList=new ArrayList<T>();
		try {
			resultList=session.createQuery("FROM "+pojo).list();
		} catch (Exception e) {
			System.out.println("----------------------------------------------------------------------------------------------------");
			System.out.println("Error in GenericDAO - getAllData Method :");
			e.printStackTrace();
			System.out.println("----------------------------------------------------------------------------------------------------");
		}
		return resultList;
	}
	
	//Generic method to add a new object to a table
	public void addData(T dataObject){
		try {
			session.save(dataObject);
		} catch (Exception e) {
			transaction.rollback();
			System.out.println("----------------------------------------------------------------------------------------------------");
			System.out.println("Error in GenericDAO - addData() Method :");
			e.printStackTrace();
			System.out.println("----------------------------------------------------------------------------------------------------");
		}
	}
	
}
